﻿using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.Collections;
using UnityEditor.XCodeEditor;


#if UNITY_IOS
using UnityEditor.iOS.Xcode;
#endif
using System.IO;
using System.Linq;

public class IOSPostBuildProcessor {
	
	// a normal post process method which is executed by Unity
	[PostProcessBuild]
	public static void OnPostprocessBuild(BuildTarget buildTarget, string pathToBuiltProject)
	{
		#if UNITY_IOS
		
		Debug.Log("OnPostprocessBuildiOS: "+ pathToBuiltProject);
		string projPath = pathToBuiltProject + "/Unity-iPhone.xcodeproj/project.pbxproj";

		//得到xcode工程的路径
		string path = Path.GetFullPath (pathToBuiltProject);

		PBXProject proj = new PBXProject ();
		proj.ReadFromString (File.ReadAllText (projPath));
		
		string target = proj.TargetGuidByName ("Unity-iPhone");
		
		// Set a custom link flag
		proj.AddBuildProperty (target, "OTHER_LDFLAGS", "-all_load");
		proj.AddBuildProperty (target, "OTHER_LDFLAGS", "-ObjC");
		
		// add frameworks
		proj.AddFrameworkToProject(target, "StoreKit.framework", true);  //IOS framework.
		proj.AddFrameworkToProject(target, "libsqlite3.0.dylib", true /*not weak*/);  //???
		proj.AddFrameworkToProject(target, "CoreTelephony.framework", true);  

		// 3rd.Framework
	    //CopyAndReplaceDirectory("Assets/Lib/mylib.framework", Path.Combine(path, "Frameworks/mylib.framework"));
//		proj.AddFileToBuild(target, proj.AddFile("Frameworks/mylib.framework", "Frameworks/mylib.framework", PBXSourceTree.Source));

//		proj.SetBuildProperty(target, "FRAMEWORK_SEARCH_PATHS", "$(inherited)123");
		proj.AddBuildProperty(target, "HEADER_SEARCH_PATHS", "$(SRCROOT)/Libraries/Plugins/iOS/AliPay/AliPaySDK/");
		proj.AddBuildProperty(target, "HEADER_SEARCH_PATHS", "$(SRCROOT)/Libraries/Plugins/iOS/AliPay/AliPaySDK/Util");
		proj.AddBuildProperty(target, "HEADER_SEARCH_PATHS", "$(SRCROOT)/Libraries/Plugins/iOS/AliPay/AliPaySDK/openssl");
		proj.AddBuildProperty(target, "HEADER_SEARCH_PATHS", "$(SRCROOT)/Libraries/Plugins/iOS/WeixinPaySDK/WeixinPaySDK/");
		proj.AddBuildProperty(target, "HEADER_SEARCH_PATHS", "$(SRCROOT)/Libraries/Plugins/iOS/WeixinPaySDK/WeixinPaySDK/lib");

		proj.UpdateBuildProperty(target, "CODE_SIGN_IDENTITY[sdk=iphoneos*]", new string[]{"iPhone Distribution"}, null);

		File.WriteAllText (projPath, proj.WriteToString ());

		// Get plist
		string plistPath = pathToBuiltProject + "/Info.plist";
		PlistDocument plist = new PlistDocument();
		plist.ReadFromString(File.ReadAllText(plistPath));
		
		// Get root
		PlistElementDict rootDict = plist.root;
		
		// Change value of CFBundleVersion in Xcode plist
//		rootDict.SetString("CFBundleVersion","1.0.3"); //Build
//		rootDict.SetString("CFBundleShortVersionString","1.0.3");
		rootDict.SetString("CFBundleDevelopmentRegion","China");  //change en=>chinese
		rootDict.SetString("CFBundleIdentifier","com.CodePiaogames.${PRODUCT_NAME}");  //change en=>chinese
		//alipay.

		//White list.
		PlistElementArray array = rootDict.CreateArray("LSApplicationQueriesSchemes");
		array.AddString("weixin");

		//OpenURL
		PlistElementArray array1 = rootDict.CreateArray("CFBundleURLTypes");
		PlistElementDict dic = array1.AddDict();
		dic.SetString("CFBundleTypeRole", "Editor");
		dic.SetString("CFBundleURLName", "weixin");
		PlistElementArray array2 = dic.CreateArray("CFBundleURLSchemes");
		array2.AddString("wx888888888888");  //weixin

		//编辑代码文件
		EditorCode(path);

		// Write to file
		File.WriteAllText(plistPath, plist.WriteToString());
		#endif
	}

	private static void EditorCode(string filePath)
	{
		//读取UnityAppController.mm文件
		XClass UnityAppController = new XClass(filePath + "/Classes/UnityAppController.mm");
		        
		//在指定代码后面增加一行代码: import "header.h"
		UnityAppController.WriteBelow("#include \"PluginBase/AppDelegateListener.h\"","#import \"WeixinPayIOSWrap.h\" \r #import <AlipaySDK/AlipaySDK.h> \r #import <PgySDK/PgyManager.h>");
		
		//在指定代码中替换一行: didFinishLaunchingWithOptions
		UnityAppController.WriteBelow("[KeyboardDelegate Initialize];","[[PgyManager sharedPgyManager] startManagerWithAppId:@\"d2d78b9aa85b58af0edb7bb78bd2b528\"]; ");
		
		//在指定代码后面增加一行: OpenURL
		UnityAppController.WriteBelow("AppController_SendNotificationWithArg(kUnityOnOpenURL, notifData);", 
		                              "[WXApi handleOpenURL:url delegate:[WeixinPayIOSWrap single]]; \r  [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {}];");	
	}

	internal static void CopyAndReplaceDirectory(string srcPath, string dstPath)
	{
		if (Directory.Exists(dstPath))
			Directory.Delete(dstPath);
		if (File.Exists(dstPath))
			File.Delete(dstPath);
		
		Directory.CreateDirectory(dstPath);
		
		foreach (var file in Directory.GetFiles(srcPath))
			File.Copy(file, Path.Combine(dstPath, Path.GetFileName(file)));
		
		foreach (var dir in Directory.GetDirectories(srcPath))
			CopyAndReplaceDirectory(dir, Path.Combine(dstPath, Path.GetFileName(dir)));
	}
}